package cn.imfc.tyss.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: zhangzhigang
 * \* Date: 2018/8/9
 * \* Time: 下午1:57
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * 读取datasource1数据源
 * \
 */
//注册到Spring Boot
@Configuration
@MapperScan(basePackages = "cn.imfc.tyss.test2",sqlSessionFactoryRef = "test2SqlSessionFactory")
public class DataSource2Config {

    /**
     * 配置test2数据源
     * @return
     */
    @Bean(name = "test2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource testDataSource(){
        return DataSourceBuilder.create().build();
    }

    /**
     * 获取SessionFactory
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "test2SqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory  (@Qualifier("test2DataSource")DataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource); // 使用titan数据源, 连接titan库
        // bean.setMapperLocations(
        // new PathMatchingResourcePatternResolver().getResources("classpath:/com/example/demo/mapper/account/*.xml"));
        return bean.getObject();

    }


    /**
     * 获取事务日志信息
     * @param dataSource
     * @return
     */
    @Bean(name = "test2TransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource")DataSource dataSource) throws Exception{
        return new DataSourceTransactionManager(dataSource);
    }


    @Bean(name = "test2SqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier ("test2SqlSessionFactory")SqlSessionFactory sqlSessionFactory)throws Exception{
        return  new SqlSessionTemplate(sqlSessionFactory);
    }


}